package io.seata.sample.service.impl;

import io.seata.sample.dao.AccountMapper;
import io.seata.sample.feign.OrderApi;

import java.math.BigDecimal;

import io.seata.sample.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: linKe
 * @Date: 2022/1/25 10:44
 * @FileName: AccountServiceImpl
 * @version: 1.0
 * @Description: 描述
 */
@Service("accountServiceImpl")
public class AccountServiceImpl implements AccountService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Resource
    private AccountMapper accountMapper;

    @Autowired
    private OrderApi orderApi;

    /**
     * 扣减账户余额
     *
     * @param userId 用户id
     * @param money  金额
     */
    @Override
    public void decrease(Long userId, BigDecimal money) {
        LOGGER.info("------->扣减账户开始account中");
        LOGGER.info("[{},{}]",userId,money);
        //模拟超时异常，全局事务回滚
//                try {
//                    //Thread.sleep(30*1000);
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
        /// System.out.println(1/0);
        // 测试分布式事务异常处理

        accountMapper.decrease(userId, money);
        LOGGER.info("------->扣减账户结束account中");

        //修改订单状态，此调用会导致调用成环
        LOGGER.info("修改订单状态开始");
        String mes = orderApi.update(userId, money.multiply(new BigDecimal("0.09")), 0);
        LOGGER.info("修改订单状态结束：{}", mes);
    }
}

